import { ApiResponse, ApiError } from '../types';

// Cursor API的URL
const API_ENDPOINT = 'https://api.cursor.so/classify';

/**
 * 分析书签，使用Cursor API进行分类
 * @param title 书签标题
 * @param url 书签URL
 * @param apiKey 用户的API密钥
 */
export const analyzeBookmark = async (
  title: string, 
  url: string, 
  apiKey: string
): Promise<ApiResponse> => {
  try {
    // 准备请求负载
    const payload = {
      title,
      url,
    };

    // 发送请求到Cursor API
    const response = await fetch(API_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify(payload),
    });

    // 检查响应状态
    if (!response.ok) {
      const errorData = await response.json();
      throw {
        error: errorData.message || '请求失败',
        status: response.status,
      } as ApiError;
    }

    // 解析和返回结果
    const data = await response.json();
    return {
      category: data.category,
      confidence: data.confidence || 0.8,
    };
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
}; 